package com.scpii.api.common.auth;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;

public class ClientAuthentication extends AbstractAuthenticationToken {

	private static final long serialVersionUID = -4809832298438307309L;

	private final AuthorizationRequest authorizationRequest;

	private final Authentication userAuthentication;

	public ClientAuthentication(AuthorizationRequest authorizationRequest,
			Authentication userAuthentication) {
		super(userAuthentication == null ? authorizationRequest
				.getAuthorities() : userAuthentication.getAuthorities());
		this.authorizationRequest = authorizationRequest;
		this.userAuthentication = userAuthentication;
	}

	public Object getCredentials() {
		return "";
	}

	public Object getPrincipal() {
		return this.userAuthentication == null ? this.authorizationRequest
				.getAppId() : this.userAuthentication.getPrincipal();
	}

	public boolean isClientOnly() {
		return userAuthentication == null;
	}

	public AuthorizationRequest getAuthorizationRequest() {
		return authorizationRequest;
	}

	public Authentication getUserAuthentication() {
		return userAuthentication;
	}

	@Override
	public boolean isAuthenticated() {
		return this.authorizationRequest.isApproved()
				&& (this.userAuthentication == null || this.userAuthentication
						.isAuthenticated());
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (!(o instanceof ClientAuthentication)) {
			return false;
		}
		if (!super.equals(o)) {
			return false;
		}

		ClientAuthentication that = (ClientAuthentication) o;

		if (!authorizationRequest.equals(that.authorizationRequest)) {
			return false;
		}
		if (userAuthentication != null ? !userAuthentication
				.equals(that.userAuthentication)
				: that.userAuthentication != null) {
			return false;
		}

		return true;
	}

	@Override
	public int hashCode() {
		int result = super.hashCode();
		result = 31 * result + authorizationRequest.hashCode();
		result = 31
				* result
				+ (userAuthentication != null ? userAuthentication.hashCode()
						: 0);
		return result;
	}

}
